package com.videoaggre.zcl.utils

import android.app.Activity
import android.content.*
import android.content.pm.PackageManager
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.location.LocationManager
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.provider.Settings
import android.text.TextUtils
import android.util.TypedValue
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.videoaggre.zcl.App
import com.videoaggre.zcl.ui.dialog.showAlertDialog
import com.yanzhenjie.sofia.Utils
import java.io.*

/**
 * Created by Administrator on 2017/3/21 0021.
 */
object Utils {
    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private const val MIN_CLICK_DELAY_TIME = 300
    private var lastClickTime: Long = 0

    /**
     * 限制重复点击
     *
     * @param minClickDelayTime
     * @return true，没有重复点击；false，minClickDelayTime 内连续点击两次
     */
    fun notRepeatClick() = notRepeatClick(MIN_CLICK_DELAY_TIME)

    /**
     * 限制重复点击
     *
     * @return true，没有重复点击；false，300ms 内连续点击两次
     */
    fun notRepeatClick(minClickDelayTime: Int): Boolean {
        val curClickTime = System.currentTimeMillis()
        if (curClickTime - lastClickTime >= minClickDelayTime) {
            lastClickTime = curClickTime
            return true
        }
        lastClickTime = curClickTime
        return false
    }

    fun isEmpty(str: String?): Boolean {
        return str == null || str.isEmpty()
    }

    fun defaultIsEmpty(str: String?, defaultStr: String): String {
        return (if (isEmpty(str)) defaultStr else str)!!
    }

    fun isTextViewValueEmpty(textView: View): Boolean {
        return isEmpty(getTextViewValue(textView))
    }

    fun getTextViewValue(textView: View): String {
        return getTextViewValue(textView as TextView)
    }

    fun getTextViewValue(textView: TextView): String {
        return textView.text.toString().trim { it <= ' ' }
    }

    fun callPhoneUrl(context: Context, url: String?) {
        val intent = Intent(Intent.ACTION_DIAL, Uri.parse(url))
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)
    }

    fun callPhone(context: Context, phone: String) {
        val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$phone"))
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)
    }

    fun setTextNotEmpty(view: TextView, value: Any?, def: String?) {
        view.text = if (value == null || value is String && isEmpty(
                value as String?
            )
        ) def else value.toString() + ""
    }

    fun setTextNotEmpty(view: TextView, value: Any?) {
        setTextNotEmpty(view, value, "")
    }

    fun replaceStar(text: String, startIndex: Int, endIndex: Int): String {
        if (!TextUtils.isEmpty(text) && startIndex <= endIndex) {
            val chars = text.toCharArray()
            val start = Math.max(startIndex, 0)
            val size = Math.min(endIndex, text.length - 1)
            for (i in start..size) {
                chars[i] = '*'
            }
            return String(chars)
        }
        return text
    }

    @JvmStatic
    fun getAppRootPath(context: Context): File {
        return if (sdCardIsAvailable()) {
            Environment.getExternalStorageDirectory()
        } else {
            context.filesDir
        }
    }

    fun setDefaultStatusBarFont(activity: Activity?) {
        setDefaultStatusBarFont(activity, true)
    }

    fun setDefaultStatusBarFont(activity: Activity?, darkFont: Boolean) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Utils.setStatusBarDarkFont(activity, darkFont)
        }
    }

    fun invasionStatusBar(activity: Activity?) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Utils.invasionStatusBar(activity)
        }
    }

    fun toastMessageShort(text: String?) {
        Toast.makeText(App.app, text, Toast.LENGTH_SHORT).show()
    }

    fun toastMessageLong(text: String?) {
        Toast.makeText(App.app, text, Toast.LENGTH_LONG).show()
    }

    fun sdCardIsAvailable(): Boolean {
        return if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            Environment.getExternalStorageDirectory().canWrite()
        } else false
    }

    fun saveImageToGallery(context: Context, bmp: Bitmap): Boolean {
        try {
            // 首先保存图片
            val storePath = Environment.getExternalStorageDirectory()
                .absolutePath + File.separator + "salon_m"
            val appDir = File(storePath)
            if (!appDir.exists()) {
                appDir.mkdir()
            }
            val fileName = System.currentTimeMillis().toString() + ".jpg"
            val file = File(appDir, fileName)
            val fos = FileOutputStream(file)
            //通过io流的方式来压缩保存图片
            val isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos)
            fos.flush()
            fos.close()
            //把文件插入到系统图库
            MediaStore.Images.Media.insertImage(
                context.contentResolver,
                file.absolutePath,
                fileName,
                null
            )
            //保存图片后发送广播通知更新数据库
            val uri = Uri.fromFile(file)
            context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
            return isSuccess
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return false
    }

    /**
     * 检查网络是否可用
     *
     * @param context
     * @return
     */
    fun isNetworkAvailable(context: Context): Boolean {
        val manager = context.applicationContext
            .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            ?: return false
        val networkinfo = manager.activeNetworkInfo
        return if (networkinfo == null || !networkinfo.isAvailable) {
            false
        } else true
    }

    fun getBitmapOptions(filePath: String?): BitmapFactory.Options {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        BitmapFactory.decodeFile(filePath, options)
        return options
    }

    fun duration(durationMs: Long): String {
        val duration = durationMs / 1000
        val h = duration / 3600
        val m = (duration - h * 3600) / 60
        val s = duration - (h * 3600 + m * 60)
        val durationValue: String
        durationValue = if (h == 0L) {
            asTwoDigit(m) + ":" + asTwoDigit(
                s
            )
        } else {
            asTwoDigit(h) + ":" + asTwoDigit(
                m
            ) + ":" + asTwoDigit(s)
        }
        return durationValue
    }

    /**
     * 时间格式化
     */
    fun formattedTime(second: Long): String {
        val hs: String
        val ms: String
        val ss: String
        val formatTime: String
        val h: Long
        val m: Long
        val s: Long
        h = second / 3600
        m = second % 3600 / 60
        s = second % 3600 % 60
        hs = if (h < 10) {
            "0$h"
        } else {
            "" + h
        }
        ms = if (m < 10) {
            "0$m"
        } else {
            "" + m
        }
        ss = if (s < 10) {
            "0$s"
        } else {
            "" + s
        }
        formatTime = if (h > 0) {
            "$hs:$ms:$ss"
        } else {
            "$ms:$ss"
        }
        return formatTime
    }

    fun asTwoDigit(digit: Long): String {
        var value = ""
        if (digit < 10) {
            value = "0"
        }
        value += digit.toString()
        return value
    }

    /**
     * 复制文本到剪切板
     *
     * @param context
     * @param text
     */
    fun setClipText(context: Context?, text: String?) {
        if (context == null) return
        val myClipboard =
            context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager?
        myClipboard?.setPrimaryClip(ClipData.newPlainText(null, text))
    }

    /**
     * 根据比例转化实际数值为相对值
     *
     * @param gear 档位
     * @param max  最大值
     * @param curr 当前值
     * @return 相对值
     */
    fun filtNumber(gear: Int, max: Int, curr: Int): Int {
        return curr / (max / gear)
    }

    fun getMeatIcon(
        context: Context,
        clz: Class<*>,
        key: String?
    ): Int {
        try {
            val info = context.packageManager
                .getApplicationInfo(context.packageName, PackageManager.GET_META_DATA)
            val welcomePath = info.metaData.getString(key)
            val fields = clz.fields
            for (field in fields) {
                val substring = welcomePath!!.substring(
                    welcomePath.lastIndexOf("/") + 1,
                    welcomePath.lastIndexOf(".")
                )
                if (field.name == substring) {
                    return field[null] as Int
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }

    fun getMeatDataString(context: Context, key: String?): String? {
        try {
            val info = context.packageManager
                .getApplicationInfo(context.packageName, PackageManager.GET_META_DATA)
            return info.metaData.getString(key)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    // 将Bitmap转换成InputStream(压缩率quality、100表示不压缩、10表示压缩90%)
    fun Bitmap2InputStream(bm: Bitmap, quality: Int): InputStream {
        val baos = ByteArrayOutputStream()
        bm.compress(Bitmap.CompressFormat.PNG, quality, baos)
        return ByteArrayInputStream(baos.toByteArray())
    }

    // 将Bitmap转换成InputStream
    fun Bitmap2InputStream(bm: Bitmap): InputStream {
        val baos = ByteArrayOutputStream()
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        return ByteArrayInputStream(baos.toByteArray())
    }

    fun showView(vararg view: View?) {
        if (view != null && view.size > 0) {
            for (viewItem in view) {
                showView(viewItem)
            }
        }
    }

    fun showView(view: View?) {
        if (view != null && view.visibility == View.GONE) {
            view.visibility = View.VISIBLE
        }
    }

    fun hideView(vararg view: View?) {
        if (view != null && view.size > 0) {
            for (viewItem in view) {
                hideView(viewItem)
            }
        }
    }

    fun hideSoftInput(activity: Activity?) {
        try {
            hideSoftInput(activity?.window?.currentFocus)
        } catch (e: Exception) {
            Logger.e(e)
        }
    }

    fun hideSoftInput(view: View?) {
        try {
            if (view == null) return
            val imm =
                view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
            if (imm != null && imm.isActive) {
                imm.hideSoftInputFromWindow(view.windowToken, 0) //强制隐藏键盘
            }
        } catch (e: Exception) {
            Logger.e(e)
        }
    }

    fun showSoftInput(editText: EditText?) {
        if (editText == null) return
        val imm = editText.context
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(editText, 0)
    }

    fun hideView(view: View?) {
        if (view != null && view.visibility == View.VISIBLE) {
            view.visibility = View.GONE
        }
    }// 设置完成后返回到原来的界面

    // 判断GPS模块是否开启，如果没有则开启
    fun isOpenGPS(): Boolean = ActivityManger.getCurActivity()?.let {
        val locationManager = it.getSystemService(Context.LOCATION_SERVICE) as LocationManager?
        if (locationManager != null) {
            if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                it.showAlertDialog {
                    message(message = "请先开启GPS")
                    positiveButton(name = "去开启") { it.startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)) }
                    negativeButton {}
                }
                false
            } else
                true
        } else {
            false
        }
    } ?: false

    fun isNetworkAvailabe(var0: Context): Boolean {
        var var1: NetworkInfo
        return if ((var0.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
                .also { var1 = it } != null
        ) var1.isAvailable else false
    }

    fun checkGPSOpen(context: Context?): Boolean {
        val locationManager = App.app
            .getSystemService(Context.LOCATION_SERVICE) as LocationManager
        return locationManager == null || locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
    }

    fun isConnected(context: Context?): Boolean {
        val conn = App.app
            .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val info = conn.activeNetworkInfo
        return info != null && info.isConnected
    }

    fun isWifi(context: Context?): Boolean {
        val connectivityManager = App.app
            .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetInfo = connectivityManager.activeNetworkInfo
        return activeNetInfo != null && activeNetInfo.type == ConnectivityManager.TYPE_WIFI
    }

    fun random8(): Int {
        val random = StringBuilder()
        for (i in 0..7) {
            random.append((Math.random() * 10).toString())
        }
        return random.toString().toInt()
    }

    fun getDouble(d: String?): String {
        var d = d
        if (d == null || d.length == 0) return "0"
        d = d.replace("0+?$".toRegex(), "") //去掉后面无用的零
        d = d.replace("[.]$".toRegex(), "") //如小数点后面全是零则去掉小数点
        return d
    }

    fun dp2px(dp: Float): Float {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dp,
            Resources.getSystem().displayMetrics
        )
    }

    /**
     * 获取屏幕宽度像素值
     *
     * @return
     */
    val screenWidth: Int
        get() {
            val resources = App.app.resources
            val dm = resources.displayMetrics
            return dm.widthPixels
        }

    fun joinQQGroup(
        activity: Activity,
        qqQun: String,
        qqQunOpenUri: String?
    ) {
        if (!TextUtils.isEmpty(qqQunOpenUri)) {
            val intent = Intent()
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            try {
                intent.data = Uri.parse(qqQunOpenUri)
                activity.startActivity(intent)
            } catch (e: Exception) {
                Logger.e(e)
                openQQ(activity, qqQun)
            }
        } else openQQ(activity, qqQun)
    }

    private fun openQQ(activity: Activity, qqQun: String) {
        if (!TextUtils.isEmpty(qqQun)) {
            try {
                setClipText(activity, qqQun)
                toastMessageShort("复制成功")
                val intent =
                    activity.packageManager.getLaunchIntentForPackage("com.tencent.mobileqq")
                activity.startActivity(intent)
            } catch (e1: Exception) {
                toastMessageShort("请检查是否安装QQ")
                Logger.e(e1)
            }
        }
    }

    fun openQQwpa(activity: Activity, qq: String) {
        try {
            val url = "mqqwpa://im/chat?chat_type=wpa&uin=$qq"
            activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
        } catch (e: Exception) {
            Logger.e(e)
            toastMessageShort("请检查是否安装QQ")
        }
    }
}